package com.example.controller;

import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.JobParametersInvalidException;
import org.springframework.batch.core.launch.JobInstanceAlreadyExistsException;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.core.launch.JobOperator;
import org.springframework.batch.core.launch.NoSuchJobException;
import org.springframework.batch.core.repository.JobExecutionAlreadyRunningException;
import org.springframework.batch.core.repository.JobInstanceAlreadyCompleteException;
import org.springframework.batch.core.repository.JobRestartException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author XieYa
 */
@RestController
public class TestController {
    @Autowired
    private JobLauncher jobLauncher;

    @Autowired
    private Job jobLauncherDemoJob;

    @Autowired
    private JobOperator jobOperator;

    @GetMapping("/job/{msg}")
    public String job(@PathVariable("msg") String msg) throws JobInstanceAlreadyCompleteException, JobExecutionAlreadyRunningException, JobParametersInvalidException, JobRestartException {
        // 把接受到的值，传送给任务
        JobParameters parameters = new JobParametersBuilder()
                .addString("msg", msg).toJobParameters();
        // 启动任务，并把参数传递给任务
        jobLauncher.run(jobLauncherDemoJob, parameters);
        return "job success";
    }

    @GetMapping("/job2/{msg}")
    public String job2(@PathVariable("msg") String msg) throws JobParametersInvalidException, JobRestartException, JobInstanceAlreadyExistsException, NoSuchJobException {
        // 启动任务，并且添加参数
        jobOperator.start("jobOperatorDemoJob", "msg=" + msg);
        return "job2 success";
    }
}
